﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;

namespace LibCommon
{
    public enum LoggerLevel { Dummy = 5, Logger = 4, Error = 3, Warning = 2, Info = 1, Debug = 0 }

    public class FileLogger : ILogger
    {
        //static private string _logfile = Path.Combine(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase, DateTime.Now.ToString("yyyyMMdd") + ".log");
        static private string _logfile = Path.Combine(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase, DateTime.Now.ToString("yyyyMMdd") + "_" + Process.GetCurrentProcess().Id + ".log");
        static private LoggerLevel _loggerLevel = LoggerLevel.Debug;

        private readonly string _identity;

        public static string LogFile
        {
            get { return _logfile; }
            set { _logfile = value; }
        }

        public static LoggerLevel Level
        {
            get { return _loggerLevel; }
            set { _loggerLevel = value; }

        }

        public FileLogger(string identity)
        {
            this._identity = identity;
        }


        public void AppendLog(LoggerLevel level, string msg)
        {
            if (level >= _loggerLevel)
            {
                string strLevel = string.Format("{0,-10}", level);
                string processId = string.Format("{0,-7}", Process.GetCurrentProcess().Id);
                StreamWriter writer = new StreamWriter(_logfile, true, Encoding.UTF8);
                writer.WriteLine(DateTime.Now.ToString() + "  " + processId+ "  " + strLevel + "  " + _identity + "    " + msg);
                writer.Close();
            }
            // output to debug console
            Trace.WriteLine(msg);
        }

        public void WriteLog(LoggerLevel level, string msg)
        {
            AppendLog(level, msg);
        }

        public void LogLogger(string msg)
        {
            AppendLog(LoggerLevel.Logger, msg);
        }

        public  void LogError(string msg)
        {
            AppendLog(LoggerLevel.Error, msg);
        }

        public  void LogWarning(string msg)
        {
            AppendLog(LoggerLevel.Warning, msg);
        }

        public  void LogInfo(string msg)
        {
            AppendLog(LoggerLevel.Info, msg);
        }

        public  void LogDebug(string msg)
        {
            AppendLog(LoggerLevel.Debug, msg);
        }
    }
}